<script lang="ts" setup>
import { Button,Dialog,ActionSheet,showLoadingToast ,closeToast,showFailToast} from 'vant';
import { ref, reactive } from 'vue';
import { useRouter,useRoute } from 'vue-router'
import ChooseAlbum from './components/chooseAlbum.vue';
import request from '@/utils/request';
import { useUserStore } from '@/stores';
import { watchEffect } from 'vue';
import { canUseCamera } from '@/utils';
const router = useRouter()
const route = useRoute()

const userStore = useUserStore()


let selectKey = ''

const showAction = ref(false)
 function onActionSelect(item){
  
  if(item.name == '相册选择'){
    showAlbum.value.open()
  }else{
    
    setTimeout(() => {
      router.push('/camera?path=/query/upload2&type=3')
    },500)
  }
}
async function handleShowAction(key){
  const res = await canUseCamera()
  selectKey = key;
  if(res){
    showAction.value = true;
  }else{
    //无法使用自定义相机，直接调气文件上传
    showAlbum.value.open()
  }
  
}

const showAlbum = ref<any>({})
function handleUpload(base64String){
  userStore[selectKey] = base64String;
}

function toSignPage(){
  request('/api/h5/getSignInfo','POST',userStore.info)
  .then(res => {
    location.href = res
  })
}
//签名
watchEffect(() => {
  if(route.query.sign){
    getSignStatus()
  }
})
async function  getSignStatus(){
  showLoadingToast({
    message:'获取签名信息...',
    forbidClick:true
  })
  let res
  try {
   res = await request('/api/h5/getFileInfo','POST',{
      order_no:userStore.info.order_no
    },{showLoading:false})

  } catch (error) {
      closeToast()
    return
  }
    const fileRes = await fetch(res);
    const fileBlob = await fileRes.blob()
    const reader = new FileReader();
    reader.onloadend = () => {
      userStore.signUri = reader.result as string
      closeToast()
    };
    reader.readAsDataURL(fileBlob);
    
}

//submit
const showSubmittingTip = ref(false),
showCompleteTip = ref(false),
countdown = ref(180)
async function submit(){
  showSubmittingTip.value = true
  startCountdown()
  const posts = {
    ...userStore.info,
    files:[
      {
        image: formatUri(userStore.idcardFaceUri),
        file_type: '02'
      },
      {
        image: formatUri(userStore.idcardBackUri),
        file_type: '03'
      },
      {
        image: formatUri(userStore.faceUri),
        file_type: '04'
      },
      {
        image: formatUri(userStore.signUri),
        file_type: '05'
      }
    ]
  }
    try {
      await request('/api/h5/uploadFile','POST', posts, {showLoading:false})
    } catch (error) {
      showSubmittingTip.value = false
      countdown.value = 180
      return
    }
  queryOrderStatus()
}
function formatUri(uri){
 return uri.replace(/^data:.*?base64,/,'')
}
function queryOrderStatus(){
  
  const next = () => {
    request('/api/h5/fileStatus','POST', {
      order_no: userStore.info.order_no
    },{
      showLoading:false
    })
    .then(() => {
      showCompleteTip.value = true
      showSubmittingTip.value = false
    })
    .catch(err => {
      if(err.code == 201){
        setTimeout(() => {
          if(countdown.value > 0){
            next()
          }else{
            showFailToast('请求超时')
            showSubmittingTip.value = false
            countdown.value = 180
          }
        }, 1000);
      }else if(err.code == 400){
        showSubmittingTip.value = false
        userStore.$reset()
        router.push('/query/login')
      }else{
        showSubmittingTip.value = false
        countdown.value = 180
      }
    })
  }
  next()
}
function startCountdown(){
  const next = () => {
    if(countdown.value <= 0){
      countdown.value = 0
      return
    }else{
      setTimeout(next, 1000)
    }
    countdown.value --
  }
  next()
}

function handleCompleteclick(){
  showCompleteTip.value=false
  router.push('/query/login')
}


</script>
<template>
  <div class="container-box">
    <div class="logo-box">
      上传信息查询
    </div>
    <div class="content">
      <div class="img-box">
        <div class="left">
          <div class="text1">人像照</div>
          <div class="text2">上传您的人像照片</div>
        </div>
        <div @click="handleShowAction('faceUri')" class="right">
            <img  v-if="userStore.faceUri" :src="userStore.faceUri" class="bg" alt="" >
        <img v-else src="@/assets/query/face.png" class="bg" alt="" >
        <img class="seal" src="@/assets/query/seal.png" alt="">
        </div>
      </div>
      <div style="margin-top: 20px;" class="img-box">
        <div class="left">
          <div class="text1">授权签字照</div>
          <div class="text2">上传授权文件签字照</div>
        </div>
        <div  @click="toSignPage" class="right">
        <img v-if="userStore.signUri" src="@/assets/query/signed.png" class="bg" alt="">
        <img v-else src="@/assets/query/sign.png" class="bg" alt="">
        <img class="seal" src="@/assets/query/seal.png" alt="">
        </div>
      </div>
      <Button type="primary" @click="submit" :disabled="!userStore.faceUri&&!userStore.signUri" style="margin-top: 36px;" block>查询</Button>
    </div>
  </div>
  <Dialog  v-model:show="showSubmittingTip"  :show-confirm-button="false">
      <div class="dialog">
        <img class="time" src="@/assets/query/time.png"/>
        <div class="tips">
          资料提交中，请耐心等待...
        </div>
        <div class="countdown">倒计时 <span>{{countdown}}S</span></div>
      </div>
  </Dialog>
  <Dialog  v-model:show="showCompleteTip"  :show-confirm-button="false">
      <div class="dialog">
        <div class="tips">
          您的申请已受理
        </div>
        <img class="time" src="@/assets/query/success.png"/>
        <Button block @click="handleCompleteclick" style="margin-top: 30px" type="primary">我知道了</Button>
      </div>
  </Dialog> 

  <ActionSheet v-model:show="showAction" cancel-text="取消" close-on-click-action  :actions="[
    {
      name:'拍照'
    },
    {
      name:'相册选择'
    }
  ]" @select="onActionSelect" />
  <ChooseAlbum @on-confirm="handleUpload"  ref="showAlbum"/>
</template>
<style lang="less" scoped>
.container-box {
  .logo-box {
    font-size: 31px;
    font-weight: bold;
    color: #fff;
    text-align: center;
  }

  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;


  .content {
    border-radius: 10px;
    width: var(--content-width);
    margin: 40px auto 0;
    background-color: #fff;
    padding: 50px 20px 25px;
    .img-box {
      border-radius:6px;
      display: flex;
      align-items: center;
      background-color: rgb(244, 246, 255);
      padding: 17px 8px;
      justify-content: center;
      .left{
        margin-right: 4px;
        .text1{
          font-size: 18px;
          font-weight: 500;
          color: #333;
        }
        .text2{
          font-size: 12px;
          color: #767676;
          margin-top:7px;
        }

      }
      .right{
        position: relative;
        .bg{
          width: 176px;
          height: 104px;
        }
        .seal {
        position: absolute;
        width:50px;
        height:50px;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
      }

      
    }
  }
}
.dialog{
  padding: 15px;
  display: flex;
  align-items: center;
  flex-direction: column;
  .time{
    width: 80px;
  }
  .tips{
    margin:20px 0 30px;
    color:#1A1A1A;
    font-size: 20px;
    font-weight: 500;
  }
  .success-img{

  }
  .countdown{
    color:#767676;
    font-weight: normal;
    font-size: 16px;
    span{
      color: #CA1919;
    }
  }
}
</style>